package Service;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Arrays;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;


public class DeepSeekService {
    String url = "https://api.deepseek.com/chat/completions";
    String key = "sk-34f54287f5414d79b732e1b17f356036";
    public String call(String message){

        String jsonString = "{\n" +
                "  \"model\": \"deepseek-chat\",\n" +
                "  \"messages\": [\n" +
                "    {\n" +
                "      \"content\": \""+message+"\",\n" +
                "      \"role\": \"user\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .header("Authorization", "Bearer "+key)
                .POST(HttpRequest.BodyPublishers.ofString(jsonString))
                .build();

        //创建client以发送请求
        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response;
        try {
            //发送请求并接受相应
             response = client.send(request,HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }

        return extract(response.body());
    }
  public static void main(String[] args) throws IOException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        new DeepSeekService().call("泥嚎！");
    }

    //裁剪出代码再去除转义字符
    public String extract(String json){
        //提取字符串内容
        int contentIndex = json.indexOf("\"content\":\"")+11;
        int end = json.indexOf(";",contentIndex);
        return json.substring(contentIndex,end).replaceAll("\\\\","")+";";
    }
}
